
window.onload = function(){
    let user = document.getElementById('userId');
    let connmsg = document.getElementById('connMsg'); //连接信息状态
    let sendMessage = document.getElementById('sendMessage'); //发送的消息
    let sendButton = document.getElementById('sendButton');
    let createConnectionButton = document.getElementById('createConnectionButton'); //创建连接按钮
    let closeConnectionButton = document.getElementById('closeConnectionButton');   //关闭连接按钮
    let chatContentUl = document.querySelector('.chatContent-ul');
    
    let ws;
    createConnectionButton.onclick = function() {
        if(!("WebSocket" in window)) {
            alert("您的浏览器不支持 WebSocket!");
            return;
        };
        //readyState状态：0连接、1开放、2-闭幕、3封闭
        if(!!!ws || ws.readyState !=  WebSocket.OPEN) {
            ws = new WebSocket("ws://10.1.90.41:8010/webSocketServer");
            ws.onopen = function(event){
                if(event.isTrusted) connmsg.innerHTML = '连接成功';
                else connmsg.innerHTML = '连接失败';
            };
        }else alert('已连接请勿重复操作！');
        
    }
    
    createConnectionButton.onclick(); //自动连接

    let sendMsg = new Object();
    sendButton.onclick = function() {
        if(!!!ws || ws.readyState !=  WebSocket.OPEN) {
            connmsg.innerText = '连接没有开启！';
            return;
        }

        if(sendMessage.value.trim() == '') {
            alert('发送内容不能为空');
            return;
        }
        
        sendMsg.msg = sendMessage.value;
        sendMsg.userId = user.value;

        ws.send(JSON.stringify(sendMsg));
        sendMessage.value = '';
        for (var key in sendMsg) delete sendMsg[key]; //删除所有属性

        ws.onmessage = function(m){
            console.log('接收到服务器信息: %s', m.data);
            let returnJson = JSON.parse(m.data);
            if(user.value.trim() == '') user.value = returnJson.sessionId;
            if(returnJson.userId.trim() == '') returnJson.userId = returnJson.sessionId;
            let l = document.createElement('li');
            l.innerHTML = `<div class="userName">${returnJson.userId}</div><div class="content">${returnJson.msg}</div>`;
            chatContentUl.appendChild(l);
        }

        ws.onclose = function(e) {
            connmsg.innerText = '与服务器连接断开！';
        }
    }
    
    user.onchange = function() {
        userId = this.value;
    }
    document.getElementById('closeConnectionButton').onclick = function() { //关闭连接
        if(!!ws) ws.close(); 
        connmsg.innerText = '连接断开';
    }

    //获取css样式
    // function getStyle(obj, name){ //获取对象当前正在使用的样式(只读)、设置样式可以通过obj.style.width = "100px";
    //         return window.getComputedStyle?window.getComputedStyle(obj,null)[name]:obj.currentStyle[name];//后面是IE8获取的方式
    // }
}